package cn.thens.kdroid.core.storage

import android.util.LruCache

class LruCacheStorage<K, V>(private val cache: LruCache<K, V>) : Storage<K, V> {
    override fun node(key: K): Storage.Node<V> {
        return Node(cache, key)
    }

    override fun clear() {
        cache.evictAll()
    }

    override fun getAll(): Map<K, V> {
        return cache.snapshot()
    }

    override fun getKeys(): Set<K> {
        return cache.snapshot().keys
    }

    class Node<K, V>(private val cache: LruCache<K, V>, private val key: K) : Storage.Node<V> {
        override fun get(): V {
            return cache.get(key)!!
        }

        override fun put(value: V) {
            cache.put(key, value)
        }

        override fun clear() {
            cache.remove(key)
        }

        override fun exists(): Boolean {
            return optional() != null
        }
    }
}
